using System;
using System.Reflection;

namespace Sedna.Core
{
	/// <summary>
	/// Codes of exceptions that are thrown by Sedna Web UI.
	/// </summary>
	public class SednaExceptionCodes
	{
		private SednaExceptionCodes()
		{
		}

		public static readonly int

		NoErrorCode = 0,
        UnknownError = 1,

        # region Sedna.Core.Security: 8000 - 8999
		
		ActionNotFound = 8000,
		ActionExecutionForbidden = 8001,
		FailedToResolveAction = 8002,
		
        # endregion

        #region Aux codes: 9000-9999

        BeginAuxExceptionCode = 9000,
        NotAuthenticated = 9001,
        NotAuthorizedOperation = 9002,
        EndAuxExceptionCode = 9999,
        
		#endregion
	    
        #region Infra codes: 13000 - 13999
        
		BeginInfraExceptionCode = 13000,
        ObjectIsModifiedByAnotherTx = 13001,
        UnauthoredIOOperation = 13002,
        DirectoryNotFound = 13003,
		UnauthorizedDirectoryAccess = 13004,
        EndInfraExceptionCode = 13999
        
		#endregion
		
	    
;

		/// <summary>
		/// Convenience method to enable usage exception code names in configuration files 
		/// instead of codes themselves.
		/// </summary>
		/// <param name="exceptionCodeName">Exception code name</param>
		/// <returns>Exception code</returns>
		public static int Parse(string exceptionCodeName)
		{
			Type type=typeof(SednaExceptionCodes);
			FieldInfo field=type.GetField(exceptionCodeName, BindingFlags.Public|BindingFlags.Static);
			if (field==null)
			{
				throw new NotSupportedException("Exception code with name \""+exceptionCodeName+"\" not found.");
			}
			return (int)field.GetValue(null);
		}

		public static string Code2Field(int code)
		{
			Type type=typeof(SednaExceptionCodes);
			FieldInfo[] fields = type.GetFields(BindingFlags.Public|BindingFlags.Static);
			foreach(FieldInfo field in fields)
			{
				if(field.FieldType != typeof(Int32))
				{
					continue;
				}
				int value = (int)field.GetValue(null);
				if(code == value)
				{
					return field.Name;
				}
			}
			throw new NotSupportedException("Exception with code = " + code + " is not declared in " + typeof(SednaExceptionCodes));
		}
		
	}
}
